from myapp import db
from datetime import datetime

organization_resource_table = db.Table('sys_organization_resource', db.metadata,
                                       db.Column('resource_id', db.String, db.ForeignKey('sys_resource.id')),
                                       db.Column('organization_id', db.String, db.ForeignKey('sys_organization.id')))


class Organization(db.Model):
    __tablename__ = 'sys_organization'
    id = db.Column(db.String(36), primary_key=True)
    create_time = db.Column(db.DateTime, index=True, default=datetime.now)
    update_time = db.Column(db.DateTime, index=True, default=datetime.now)
    name = db.Column(db.String(200))
    address = db.Column(db.String(200))
    code = db.Column(db.String(200))
    iconcls = db.Column(db.String(100))
    seq = db.Column(db.Integer)
    leader = db.Column(db.String(20))
    phone = db.Column(db.String(11))
    email = db.Column(db.String(50))
    status = db.Column(db.String(10))

    resources = db.relationship('Resource', secondary=organization_resource_table,
                                backref=db.backref('organizations', lazy='dynamic'))

    organization_id = db.Column(db.String, db.ForeignKey('sys_organization.id'))

    children = db.relationship('Organization', backref=db.backref('parent', remote_side=[id]),
                            lazy='dynamic', order_by="Organization.seq")
    
    def to_json(self):
        return {
            'deptId': self.id,
            'createTime': self.create_time,
            'updateTime': self.update_time,
            'deptName': self.name,
            'address': self.address,
            'code': self.code,
            'iconCls': self.iconcls,
            'orderNum': self.seq,
            'parentId': self.get_pid(),
            'leader': self.leader,
            'phone': self.phone,
            'email': self.email,
            'status': self.status,
            'children': [
                org.to_json() for org in self.children
            ]
        }
    
    def to_tree_select_json(self):
        return {
            'id': self.ID,
            'label': self.name,
            'children': [org.to_tree_select_json() for org in self.children]
        }

    def get_pid(self):
        if self.parent:
            return self.parent.ID
        return ''

    def get_id(self):
        return str(self.ID)

    def __repr__(self):
        return '<Organization %r>\n' %(self.name)